import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;

public class TestDemo {
    public static void main(String[] args) {
        int[][] arr = {{1,2,3},{4,5,6},{7,8,9}};
        matrix(arr);
        for(int i=0;i<arr.length;i++){
            System.out.println(ret[i]+" ");
        }
    }

    static int m, n;
    static int[] dx = {0, 1, 0, -1};
    static int[] dy = {1, 0, -1, 0};
    static int[] ret;
    static int index = 0;
    static boolean[][] vis;

    public static int[] matrix(int[][] arr) {
        m = arr.length;
        n = arr[0].length;
        ret = new int[m*n];
        vis = new boolean[m][n];
        dfs(arr,0,0);
        return ret;
    }

    public static void dfs(int[][] arr,int i,int j){
        Queue<int[]> q = new LinkedList<>();
        q.add(new int[]{i,j});
        ret[index++] = arr[i][j];
        vis[i][j] = true;
        while(!q.isEmpty()){
            int[] t = q.poll();
            int a = t[0]; int b = t[1];
            for(int k = 0; k<4; k++){
                int x = a+dx[k]; int y = b+dy[k];
                if(x >= 0 && x < m && y >=0 && y<n && !vis[x][y]){
                    ret[index++] = arr[x][y];
                    vis[x][y] = true;
                    q.add(new int[]{x,y});
                    break;
                }
            }
        }
    }



}
